<?php
require_once("lib/auth/user.php");
require_once("lib/sqlConnector.php");
require_once("lib/auth/identity.php");

//session_name("id");
//session_start();

if (isset($_REQUEST["sid"])) {
    //start logged in session
    $res = sqlQuery("SELECT userid FROM auth WHERE token='%s'",$_REQUEST["sid"]);
    $res = mysql_fetch_assoc($res);    
    $USERID = $res['userid'];
    $TOKEN = $_REQUEST["sid"];
} 

function loggedIn() {
    if (isset($GLOBALS['USERID'])) {
        return $GLOBALS['USERID'];
    } else {
        return 0;
    }
}

function logOut() {
    sqlQuery("DELETE * FROM auth WHERE token='%s' AND userid='%s'",array($GLOBALS['TOKEN'],$GLOBALS['USERID']));
    unset($GLOBALS['USERID']);
    unset($GLOBALS['TOKEN']);
}

function authenticate() {
    require_once("lib/auth/openid.php");
    $openid = new LightOpenID("http://".$_SERVER["HTTP_HOST"]);
    if(!$openid->mode) {
        $GLOBALS['TOKEN'] = uniqid(rand(0,9999999));
        sqlQuery("INSERT INTO auth SET token='%s'",$GLOBALS['TOKEN']);
        if(isset($_REQUEST['return'])) {
            $return = "&sidreturnsid=".$_REQUEST['return'];
        } else {
            $return = "";
        }
        $openid->returnUrl = "http://".$_SERVER["HTTP_HOST"]."/api/auth/login.php?sidtokensid=".$GLOBALS['TOKEN'].$return;
        $openid->identity = 'https://www.google.com/accounts/o8/id';
        $openid->required = array('contact/email');
        return $openid->authUrl();
    }
    return false;
}

//requires the variables from the get by google
function login() {
    require_once("lib/auth/openid.php");
    $openid = new LightOpenID("http://".$_SERVER["HTTP_HOST"]);
    if ($openid->validate()) {
        $userid = getUserId($openid->identity);
        if ($userid || $userid = registerOpenId($openid)) {
            $GLOBALS['USERID']=$userid;
            $GLOBALS['TOKEN'] = $_GET['sidtokensid'];
            sqlQuery("UPDATE auth SET userid='%s' WHERE token='%s'",array($GLOBALS['USERID'],$GLOBALS['TOKEN']));
            return $_GET['sidreturnsid'];
        } else {
            return false;
        }
        return true;
    }
    return false;
}


?>